package com.study.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.study.io.Resources;
import com.study.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;
    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element element = document.getRootElement();
        List<Element> nodes = element.selectNodes("//property");
        Properties properties = new Properties();
        for (Element node : nodes) {
            String name = node.attributeValue("name");
            String value = node.attributeValue("value");
            properties.put(name, value);
        }
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

        // 解析mapper.xml
        List<Element> mapperNodes = element.selectNodes("//mapper");
        for (Element mapperNode : mapperNodes) {
            String mapperPath = mapperNode.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parseMapper(resourceAsStream);
        }
        return configuration;
    }
}
